import {
  GetDatasetList,
  GetTargetTree,
  GetTargetTreeOriginalTarget,
  GetTargetTreeResources,
} from '@/common/types';
import { SvgIcon } from '@/components/icon';
import ModalsBoxContent from '@/components/modals/ModalsBoxContent';
import { CaretDownOutlined } from '@ant-design/icons';
import { Checkbox, Tooltip } from 'antd';
import React, { useEffect, useMemo, useState } from 'react';

interface Props {
  list: GetTargetTree[];
  selectKnow?: GetTargetTreeOriginalTarget[];
  handleClickKnow: (type: string, know?: GetTargetTree) => void;
  handleClickTreeUITree: (value: GetTargetTree) => void;
  expandedKeys: string[];
  defaultValue: any[];
  treeUIRef: React.RefObject<HTMLDivElement>;
  handleTreeUIOpen: () => void;
  openStatus: boolean;
  contentHeight: string;
}

const TreeUI = ({
  list,
  selectKnow,
  handleClickKnow,
  handleClickTreeUITree,
  expandedKeys,
  defaultValue,
  treeUIRef,
  handleTreeUIOpen,
  openStatus,
  contentHeight,
}: Props) => {
  const checkAllIdsIncluded = useMemo(() => {
    const idSetB = new Set(selectKnow?.map((item) => item.target_id));
    return defaultValue.every((item) => idSetB.has(item.id));
  }, [defaultValue, selectKnow]);

  return (
    <div>
      <div className="mr-6 flex h-10 bg-fill-1 text-cn-14-blod leading-10 text-text-3">
        <div className="flex w-1/2 items-center gap-2 pl-3">
          <div>组织人员</div>
          <Tooltip title={openStatus ? '关闭组织管理' : '展开组织管理'}>
            <div>
              <SvgIcon
                icon={openStatus ? 'node-close' : 'node-open'}
                size="16px"
                className="rotate-90 cursor-pointer"
                onClick={handleTreeUIOpen}
              />
            </div>
          </Tooltip>
        </div>
        <div className="flex w-1/2 items-center justify-center text-center">
          <Checkbox checked={checkAllIdsIncluded} onClick={() => handleClickKnow('all')}>
            问答权限
          </Checkbox>
          <Tooltip title={'该权限为独立控制，父级权限设置不影响此项'}>
            <div>
              <SvgIcon icon={'tips'} size="16px" className="cursor-pointer" />
            </div>
          </Tooltip>
        </div>
      </div>
      <ModalsBoxContent
        className=" overflow-y-auto "
        ref={treeUIRef}
        style={{
          // height: 'calc(100vh - 396px)',
          height: `calc(100vh - ${contentHeight})`,
        }}
      >
        {list.map((dataset) => (
          <TreeNode
            node={dataset}
            key={dataset.target_id}
            selectKnow={selectKnow}
            handleClickKnow={handleClickKnow}
            handleClickTreeUITree={handleClickTreeUITree}
            expandedKeys={expandedKeys}
            defaultValue={defaultValue}
          />
        ))}
      </ModalsBoxContent>
    </div>
  );
};

interface TreeNodeProps {
  node: GetTargetTree;
  level?: number;
  selectKnow?: GetTargetTreeOriginalTarget[];
  handleClickKnow: (type: string, know?: GetTargetTree) => void;
  handleClickTreeUITree: (value: GetTargetTree) => void;
  expandedKeys: string[];
  defaultValue: any[];
}

const TreeNode = ({
  node,
  level = 0,
  selectKnow,
  handleClickKnow,
  handleClickTreeUITree,
  expandedKeys,
  defaultValue,
}: TreeNodeProps) => {
  const expanded = useMemo(() => {
    return expandedKeys.includes(node.target_id);
  }, [expandedKeys]);

  const iconName = () => {
    if (node.level === 0) {
      return 'ai-classa';
    }
    if (node.level === 1) {
      return 'ai-classb';
    }

    if (node.level === 2) {
      return 'ai-calssc';
    }

    return 'ai-classd';
  };

  const select = useMemo(() => {
    return selectKnow?.find((item) => item.target_id === node.target_id);
  }, [selectKnow, node]);

  const checkStatus = useMemo(
    () => defaultValue.some((item) => item.id === node.target_id),
    [defaultValue, node],
  );

  return (
    <>
      <div className="flex h-10  border-b-[1px] border-solid border-b-line-1 text-cn-14 leading-10 text-[#1d1d1d]">
        <div
          className="flex w-1/2 items-center gap-2"
          style={{
            paddingLeft: level * 12,
          }}
        >
          <div className="flex h-6 w-6 items-center justify-center font-medium">
            {node.childrens.length > 0 && (
              <CaretDownOutlined
                onClick={() => handleClickTreeUITree(node)}
                rotate={expanded ? 0 : -90}
              />
            )}
          </div>
          <SvgIcon icon={iconName()} size="24px" />
          <div>{node.target_name}</div>
          {node.childrens.length > 0 && <div>({node.childrens.length})</div>}
        </div>
        <div className="w-1/2 text-center">
          {checkStatus && (
            <Checkbox checked={select !== undefined} onClick={() => handleClickKnow('type', node)}>
              问答
            </Checkbox>
          )}
        </div>
      </div>

      {expanded &&
        node.childrens &&
        node.childrens.map((child) => (
          <TreeNode
            node={child}
            key={child.target_id}
            level={level + 1}
            handleClickKnow={handleClickKnow}
            selectKnow={selectKnow}
            handleClickTreeUITree={handleClickTreeUITree}
            expandedKeys={expandedKeys}
            defaultValue={defaultValue}
          />
        ))}
    </>
  );
};

export default TreeUI;
